﻿using Microsoft.Extensions.DependencyInjection;
using WeDonekRpc.Client.Interface;
namespace WeDonekRpc.NetCoreModular
{
    internal class IocServiceProvider : IServiceProvider, IServiceProviderIsService, IKeyedServiceProvider, ISupportRequiredService, IServiceProviderIsKeyedService, IDisposable, IAsyncDisposable
    {
        private readonly IScoreService _Ioc;

        internal IocServiceProvider ( IScoreService ioc )
        {
            this._Ioc = ioc;
        }

        public void Dispose ()
        {
            this._Ioc.Dispose();
            GC.SuppressFinalize(this);
        }

        public async ValueTask DisposeAsync ()
        {
            await this._Ioc.DisposeAsync();
        }

        public object? GetKeyedService ( Type serviceType, object? serviceKey )
        {
            if ( serviceKey is null )
            {
                return this._Ioc.ResolveOptional(serviceType);
            }
            else
            {
                return this._Ioc.ResolveOptionalService(serviceKey, serviceType);
            }
        }

        public object GetRequiredKeyedService ( Type serviceType, object? serviceKey )
        {
            if ( serviceKey is null )
            {
                return this._Ioc.Resolve(serviceType);
            }
            else
            {
                return this._Ioc.Resolve(serviceType, serviceKey);
            }
        }

        public object GetRequiredService ( Type serviceType )
        {
            return this._Ioc.Resolve(serviceType);
        }

        public object? GetService ( Type serviceType )
        {
            if ( this._Ioc.IsRegistered(serviceType) )
            {
                return this._Ioc.Resolve(serviceType);
            }
            return null;
        }

        public bool IsKeyedService ( Type serviceType, object? serviceKey )
        {
            if ( serviceKey == null )
            {
                return this._Ioc.IsRegistered(serviceType);
            }
            return this._Ioc.IsRegistered(serviceType, serviceKey);
        }

        public bool IsService ( Type serviceType )
        {
            return this._Ioc.IsRegistered(serviceType);
        }
    }
}
